import datetime
from api.models import *
from django.shortcuts import render, redirect
from app01.models import *
from api.utils.permissions_control import is_super_fun


def backend(request):
    # 如果没有登陆
    if not request.user.username:
        return redirect('/')
    user = request.user
    collect_query = user.collects.all()
    return render(request, 'backend/backend.html', locals())


def edit_avatar(request):
    sign_status = request.user.sign_status
    avatar_list = Avatars.objects.all()
    if sign_status == 0:
        # 如果是用户名
        avatar_id = request.user.avatar.nid

    else:
        avatar_url = request.user.avatar_url
        for i in avatar_list:
            if i.url.url == avatar_url:
                avatar_id = i.nid
    return render(request, 'backend/edit_avattar.html', locals())


def reset_password(request):
    return render(request, 'backend/reset_password.html', locals())


@is_super_fun
def add_article(request):
    # 拿到所有的文章标签
    tag_list = Tags.objects.all()
    # 拿到所有的文章封面
    cover_list = Cover.objects.all()
    c_l = [{
        "url": cover.url.url,
        "nid": cover.nid
    } for cover in cover_list]

    category_list = Articles.category_choice
    return render(request, 'backend/add_article.html', locals())


@is_super_fun
def edit_article(request, nid):
    category_list = Articles.category_choice
    # 拿到所有的文章标签
    tag_list = Tags.objects.all()
    # 拿到所有的文章封面
    cover_list = Cover.objects.all()
    c_l = [{
        "url": cover.url.url,
        "nid": cover.nid
    } for cover in cover_list]

    article_obj = Articles.objects.get(nid=nid)
    tags = [str(tag.nid) for tag in article_obj.tag.all()]
    return render(request, 'backend/edit_article.html', locals())


@is_super_fun
def admin_home(request):
    # 用户总数
    user_count = UserInfo.objects.count()
    article_count = Articles.objects.count()
    moods_count = Moods.objects.count()
    email_count=Email.objects.count()
    # 今日注册
    now = datetime.date.today()
    today_sign = UserInfo.objects.filter(
        date_joined__gt=now
    ).count()

    return render(request, 'admin_home.html', locals())


# 头像列表
@is_super_fun
def avatar_list(request):
    avatar_query = Avatars.objects.all()
    return render(request, 'backend/avatar_list.html', locals())


# 文章封面
@is_super_fun
def cover_list(request):
    cover_query = Cover.objects.all()
    return render(request, 'backend/cover_list.html', locals())
